<?php

/**
 * 订单操作
 */

namespace app\order\api;

class OrderApi extends \app\member\api\MemberApi {

    private $orderInfo = [];
    private $orderStatus = [];

    public function __construct() {
        parent::__construct();
        $orderNo = $this->data['order_no'];
        if(empty($orderNo)) {
            $this->error('订单号不正确!');
        }
        $target = target('order/Order');
        $orderInfo = $target->getWhereInfo([
            'order_no' => $orderNo
        ]);
        if($orderInfo['order_user_id'] <> $this->userId) {
            $this->error('该订单无法操作!');
        }
        $this->orderInfo = $orderInfo;
        $this->orderStatus = target('order/Order', 'service')->getAction($orderInfo);
    }

    /**
     * 取消订单
     */
    public function cancel() {
        $orderInfo = $this->orderInfo;

        if($this->orderStatus['action'] <> 'pay' && $this->orderStatus['action'] <> 'parcel') {
            $this->error('无法取消该订单!');
        }
        $model = target('order/Order');
        $model->beginTransaction();
        $refund = false;
        if($this->orderStatus['action'] == 'parcel') {
            $refund = true;
        }
        if(!target('order/Order', 'service')->cancelOrder($orderInfo['order_id'], $refund)) {
            $model->rollBack();
            $this->error(target('order/Order', 'service')->getError());
        }
        $model->commit();
        $this->success('取消订单成功!');
    }

    /**
     * 确认收货
     */
    public function confirm() {
        $orderInfo = $this->orderInfo;
        if($this->orderStatus['action'] <> 'receive') {
            $this->error('无法进行确认收货!');
        }
        $model = target('order/Order');
        $model->beginTransaction();
        if(!target('order/Order', 'service')->confirmOrder($orderInfo['order_id'])) {
            $model->rollBack();
            $this->error(target('order/Order', 'service')->getError());
        }
        $model->commit();
        $this->success('确认收货成功!');
    }

    /**
     * 查看快递
     */
    public function delivery() {
        $orderInfo = $this->orderInfo;

        $num = $this->data['num'];

        $deliveryList = target('order/OrderDelivery')->loadList([
            'A.order_id' => $orderInfo['order_id']
        ], 0, 'delivery_id asc');

        $deliveryInfo = $deliveryList[$num];
        if(empty($deliveryInfo)) {
            $this->error404();
        }

        $waybillLog = target('order/Order', 'service')->getWaybillLog($deliveryInfo['delivery_id']);
        $msg = '';
        if(empty($waybillLog)) {
            $msg = target('order/Order', 'service')->getError();
            $waybillLog = [];
        }

        if(empty($waybillLog)) {
            $this->error404($msg);
        }else {

            $this->success($msg, [
                'deliveryList' => $deliveryList,
                'orderInfo' => $orderInfo,
                'num' => $num,
                'logList' => $waybillLog
            ]);
        }
    }

}
